﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Win32;

namespace CSP.Package.Controls
{
    public partial class CreateInternetWebApplication : UserControl, IInstallationControl
    {
        private const string _executionPath = @"InternetPortal\CreateWebApplication.bat";

        public CreateInternetWebApplication()
        {
            InitializeComponent();
        }

        #region IInstallationControl Members

        private Installer _form;
        public Installer GetForm()
        {
            return _form;
        }

        public void SetForm(Installer installer)
        {
            _form = installer;
        }

        private bool ValidateInputs()
        {
            if (checkBox1.Checked)
            {
                if (txbUrl.Text.Length == 0)
                {
                    MessageBox.Show(CSP.Package.labels.CspInstallError_UrlNoEmpty, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txbUrl.Focus();
                    txbUrl.Select();
                    return false;
                }
                return true;
            }
            else
            {
                if (txbPort.Text.Length > 0)
                {
                    try
                    {
                        int i = Convert.ToInt32(txbPort.Text);
                    }
                    catch
                    {
                        MessageBox.Show(CSP.Package.labels.CspInstallError_PortInteger, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txbPort.Focus();
                        txbPort.Select();
                        return false;
                    }
                }

                if (txbLogin.Text.Length == 0)
                {
                    MessageBox.Show(CSP.Package.labels.CspInstallError_LoginNoEmpty, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txbLogin.Focus();
                    txbLogin.Select();
                    return false;
                }

                if (txbEmail.Text.Length == 0)
                {
                    MessageBox.Show(CSP.Package.labels.CspInstallError_EmailNoEmpty, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txbEmail.Focus();
                    txbEmail.Select();
                    return false;
                }

                if (chkApid.Checked)
                {
                    if (txbApiduser.Text.Length == 0)
                    {
                        MessageBox.Show(CSP.Package.labels.CspInstallError_UsernameNoEmpty, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txbApiduser.Focus();
                        txbApiduser.Select();
                        return false;
                    }

                    if (txbApidpwd.Text.Length == 0)
                    {
                        MessageBox.Show(CSP.Package.labels.CspInstallError_PasswordNoEmpty, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txbApidpwd.Focus();
                        txbApidpwd.Select();
                        return false;
                    }

                    if (!txbApidpwd.Text.Equals(txbApidpwd2.Text))
                    {
                        MessageBox.Show(CSP.Package.labels.CspInstallError_PasswordNoMatch, CSP.Package.labels.CspInstallError_Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txbApidpwd.Focus();
                        txbApidpwd.Select();
                        return false;
                    }

                }

                return true;
            }
        }

        public bool Next()
        {
            try
            {
                if (ValidateInputs())
                {

                    GetForm().AddToLog("----------------------------------------------");
                    GetForm().AddToLog(CSP.Package.labels.CspInstallLog_InternetWebApplicationStart);

                    if (!checkBox1.Checked)
                    {

                        Process proces = new Process();
                        proces.StartInfo.CreateNoWindow = false;
                        proces.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        proces.StartInfo.FileName = _executionPath;
                        string arguments = string.Format(@"{0} ""{1}"" {2} {3} {4} {5}", new string[] { GetWebApplicationUrl(), GetWebApplicationDescription(), txbLogin.Text, txbEmail.Text, chkApid.Checked ? txbApiduser.Text : string.Empty, chkApid.Checked ? txbApidpwd.Text : string.Empty });

                        GetForm().AddToLog("   " + labels.CspInstallLog_Arguments + ": " + arguments);

                        proces.StartInfo.Arguments = arguments;
                        proces.StartInfo.UseShellExecute = false;
                        proces.StartInfo.RedirectStandardOutput = true;
                        proces.StartInfo.RedirectStandardError = true;
                        proces.Start();
                        string error = proces.StandardError.ReadToEnd();
                        string output = proces.StandardOutput.ReadToEnd();
                        proces.WaitForExit();
                        if (error != string.Empty)
                        {
                            throw new ApplicationException(error);
                        }

                        GetForm().AddToLog(output);
                    }

                    RegistryAccess.CreateStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, "CSPInternetWebApplication", GetWebApplicationUrl());
                    RegistryAccess.CreateStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, "CSPInternetIdentity", chkApid.Checked?txbApiduser.Text : "NT Authority\\NetworkService");
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                this.GetForm().ShowException(ex);
                throw ex;
            }

        }

        public void Previous()
        {
        }

        public void Skip()
        {
        }

        #endregion


        private void TranslateLiterals()
        {
            richTextBox1.Text = CSP.Package.labels.CreateInternetWebApplication_Intro;
            
            groupBox1.Text = CSP.Package.labels.IISWebSite_GroupBox;
            groupBox2.Text = CSP.Package.labels.ApplicationPoolCredentials_GroupBox;
            groupBox3.Text = CSP.Package.labels.OwnerInformation_GroupBox;
            groupBox4.Text = CSP.Package.labels.ExistingWebApplication_GroupBox;            

            label5.Text = CSP.Package.labels.Port_Label;
            label6.Text = CSP.Package.labels.HostHeader_Label;
            label2.Text = CSP.Package.labels.Description_Label;
            label9.Text = CSP.Package.labels.Email_Label;
            label10.Text = CSP.Package.labels.Login_Label;
            label7.Text = CSP.Package.labels.Username_Label;
            label4.Text = CSP.Package.labels.Password_Label;
            label3.Text = CSP.Package.labels.PasswordReType_Label;
            label11.Text = CSP.Package.labels.Url_Label;
            label1.Text = CSP.Package.labels.Identity_Label;
            
            checkBox1.Text = CSP.Package.labels.WebApplicationAlreadyCreatedInternet_Label;
            chkSSL.Text = CSP.Package.labels.UseSSL_Label;
            chkApid.Text  = CSP.Package.labels.Configurable_Label;                        
        }

        private string GetWebApplicationIdentity()
        {
            if (checkBox1.Checked)
            {
                return txbIdentity.Text;
            }
            else
            {
                return chkApid.Checked ? txbApiduser.Text : "NT Authority\\NetworkService";
            }
        }

        private string GetWebApplicationUrl()
        {
            if (checkBox1.Checked)
            {
                return txbUrl.Text;
            }
            else
            {
                string result = chkSSL.Checked ? "https://" : "http://";
                result += txbHostHeader.Text.Length == 0 ? "localhost" : txbHostHeader.Text;
                result += txbPort.Text.Length == 0 ? string.Empty : ":" + txbPort.Text;
                return result;
            }
        }

        private string GetWebApplicationDescription()
        {
            return string.Format("Sharepoint - {0}{1}", txbHostHeader.Text, txbPort.Text);
        }

        private void CreateInternetWebApplication_Load(object sender, EventArgs e)
        {
            TranslateLiterals();
            txbLogin.Text = Environment.UserDomainName + "\\" + Environment.UserName;

        }

        private void txbPort_TextChanged_1(object sender, EventArgs e)
        {
            txbDescription.Text = GetWebApplicationDescription();
        }

        private void txbHostHeader_TextChanged_1(object sender, EventArgs e)
        {
            txbDescription.Text = GetWebApplicationDescription();
        }

        private void chkApid_CheckedChanged_1(object sender, EventArgs e)
        {
            txbApidpwd.ReadOnly = !chkApid.Checked;
            txbApidpwd2.ReadOnly = !chkApid.Checked;
            txbApiduser.ReadOnly = !chkApid.Checked;

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            txbUrl.ReadOnly = !checkBox1.Checked;
            txbIdentity.ReadOnly = !checkBox1.Checked;
            
        }

    }
}
